﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Configuration;
using System.ComponentModel;
using System.Linq;
using BusinessLogic.Model;
using BusinessLogic;

namespace WebControls
{
    public partial class NewsItemEditor : System.Web.UI.UserControl
    {

        #region Properties

        [Category("NewsItem"), Browsable(true)]
        public NewsItem NewsItem { get; set; }
        [Category("NewsItem"), Browsable(true)]
        public bool IsEditMode { get; set; }

        #endregion

        #region Events

        [Browsable(true)]
        public event EventHandler Save;

        #endregion

        #region PageEvents

        protected void Page_Init(object sender, EventArgs e)
        {
            //load the values from the enum
            foreach (CommentsPolicy value in Enum.GetValues(typeof(CommentsPolicy)))
            {
                ListItem li = new ListItem(Enum.GetName(typeof(CommentsPolicy), value), ((byte)value).ToString());
                ddlCommentsPolicy.Items.Add(li);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            phMinorEdit.Visible = IsEditMode;
            phEditImage.Visible = IsEditMode;

            if (!IsPostBack)
            {
                //populate the controls
                if (IsEditMode)
                {
                    txtTitle.Text = NewsItem.Title.Replace(" &nbsp;", "  ").HtmlDecode();

                    ddlCommentsPolicy.SelectedValue = ((byte)NewsItem.AllowComments).ToString();

                    if (NewsItem.IsShortTextHtml)
                    {
                        txtShortText.Text = NewsItem.ShortText;
                        edShortText.Content = NewsItem.ShortText;
                        ToggleShortText(true);
                    }
                    else
                    {
                        txtShortText.Text = NewsItem.ShortText.Replace("<br />", Environment.NewLine).Replace(" &nbsp;", "  ").RemoveHtmlTags().HtmlDecode();
                        edShortText.Content = txtShortText.Text;
                        ToggleShortText(false);
                    }

                    if (!String.IsNullOrEmpty(NewsItem.Text))
                    {
                        rbFullText.Checked = true;
                        rbShortText.Checked = false;
                        pnlFullText.Visible = true;

                        if (NewsItem.IsTextHtml)
                        {
                            txtFullText.Text = NewsItem.Text;
                            edFullText.Content = NewsItem.Text;
                            ToggleFullText(true);
                        }
                        else
                        {
                            txtFullText.Text = NewsItem.Text.Replace("<br />", Environment.NewLine).Replace(" &nbsp;", "  ").RemoveHtmlTags().HtmlDecode();
                            edFullText.Content = txtFullText.Text;
                            ToggleFullText(false);
                        }
                    }
                    else
                    {
                        rbFullText.Checked = false;
                        rbShortText.Checked = true;
                        pnlFullText.Visible = false;
                    }
                }
            }

            if (IsEditMode)
            {
                //load controls for tags
                if (NewsItem.Tags.Count > 0)
                {
                    pnlCurrentTags.Visible = true;

                    pnlCurrentTags.Controls.Add(new Literal { Text = "Remove tag" });
                    pnlCurrentTags.Controls.Add(new Literal { Text = "<br />" });

                    foreach (Tag t in NewsItem.Tags)
                    {
                        //check boxes IDs start with "ID_" followed by the tag value if you change "ID_" change the index for substring when submitting
                        pnlCurrentTags.Controls.Add(new CheckBox { Checked = false, ID = "ID_" + t.TagValue });
                        pnlCurrentTags.Controls.Add(new Literal { Text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" });
                        pnlCurrentTags.Controls.Add(new Label { Text = t.TagValue });
                        pnlCurrentTags.Controls.Add(new Literal { Text = "<br />" });
                    }

                    pnlCurrentTags.Controls.Add(new Literal { Text = "<br />" });
                }
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (IsEditMode && NewsItem.Image != null)
            {
                mvImage.ActiveViewIndex = 0; //index for image View
                imgCurrentImage.ImageUrl = "~/HttpHandlers/ImageHandler.ashx?" + QueryStringConstants.NewsItemImageID + "=" + NewsItem.NewsItemID;
            }
            else
            {
                mvImage.ActiveViewIndex = 1; //index for no image View
            }

            if (!IsEditMode)
            {
                btnSave.Text = "Submit";
            }
        }

        #endregion

        #region ControlEvents

        protected void rbShortText_CheckedChanged(object sender, EventArgs e)
        {
            FullTextCheckedChanged();
        }
        protected void rbFullText_CheckedChanged(object sender, EventArgs e)
        {
            FullTextCheckedChanged();
        }

        protected void ddlIsFullTextHtml_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlIsFullTextHtml.SelectedValue == "html")
            {
                ToggleFullText(true);
            }
            else
            {
                ToggleFullText(false);
            }
        }

        protected void ddlIsShortTextHtml_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlIsShortTextHtml.SelectedValue == "html")
            {
                ToggleShortText(true);
            }
            else
            {
                ToggleShortText(false);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }

            if (!IsEditMode)
            {
                NewsItem = new NewsItem
                {
                    AuthorUsername = Page.User.Identity.Name,
                    CommentsCount = 0,
                    PostDate = DateTime.Now
                };
            }

            string shortText;
            string fullText;
            bool isShortTextHtml = ddlIsShortTextHtml.SelectedValue == "html";
            bool isFullTextHtml = rbFullText.Checked && ddlIsFullTextHtml.SelectedValue == "html";

            #region EscapeText

            if (isShortTextHtml)
            {
                shortText = edShortText.Content.Trim();
            }
            else
            {
                shortText = txtShortText.Text.HtmlEncode().TrimEnd(null).Replace("  ", " &nbsp;").Replace(Environment.NewLine, "<br />").AddHtmlTags();
            }

            if (rbFullText.Checked)
            {
                if (isFullTextHtml)
                {
                    fullText = edFullText.Content.Trim();
                }
                else
                {
                    fullText = txtFullText.Text.HtmlEncode().TrimEnd(null).Replace("  ", " &nbsp;").Replace(Environment.NewLine, "<br />").AddHtmlTags();
                }
            }
            else
            {
                fullText = null;
            }

            #endregion

            //do not update Last Edited values if the edit is minor
            if (IsEditMode && !chkMinorEdit.Checked)
            {
                NewsItem.LastEditedBy = Page.User.Identity.Name;
                NewsItem.LastEditedDate = DateTime.Now;
            }

            NewsItem.ShortText = shortText;
            NewsItem.IsShortTextHtml = isShortTextHtml;
            NewsItem.Text = fullText;
            NewsItem.IsTextHtml = isFullTextHtml;

            string title = txtTitle.Text.HtmlEncode().TrimEnd(null);
            
            //check if new title is unique
            if (!IsEditMode || (IsEditMode && title != NewsItem.Title))
            {
                BlogNETDataContext dc = new BlogNETDataContext(ConfigurationManager.ConnectionStrings["BlogNETDB"].ConnectionString);
                int result = dc.NewsItems.Count(ni => ni.Title == title);

                if (result > 0)
                {
                    lblTitleErrorMsg.Visible = true;
                    return;
                }
            }

            NewsItem.Title = title;
            NewsItem.AllowComments = (CommentsPolicy)Convert.ToByte(ddlCommentsPolicy.SelectedValue);

            if ((!IsEditMode || rbNewImage.Checked) && fuImage.FileBytes.Length > 0)
            {
                using (Bitmap image = ImageManipulator.Resize(new Bitmap(new MemoryStream(fuImage.FileBytes)),
                    Convert.ToInt32(ConfigurationManager.AppSettings["NewsItemImageWidth"]),
                    Convert.ToInt32(ConfigurationManager.AppSettings["NewsItemImageHeight"]),
                    true, false))
                {

                    using (MemoryStream stream = new MemoryStream())
                    {
                        image.Save(stream, ImageFormat.Png);
                        NewsItem.Image = new System.Data.Linq.Binary(stream.GetBuffer());
                    }
                }
            }
            else if (rbRemoveImage.Checked)
            {
                NewsItem.Image = null;
            }

            //remove current tags
            foreach (Control c in pnlCurrentTags.Controls)
            {
                CheckBox cb = c as CheckBox;

                if (cb != null && cb.Checked)
                {
                    string tagValue = cb.ID.Substring(3); //check boxes IDs start with "ID_" followed by the tag value

                    foreach (Tag t in NewsItem.Tags)
                    {
                        if (t.TagValue == tagValue)
                        {
                            //dc.Tags.DeleteOnSubmit(t);
                            NewsItem.Tags.Remove(t);
                            break;
                        }
                    }
                }
            }

            //add new tags
            foreach (Control c in pnlTags.Controls)
            {
                TextBox txtTag = c as TextBox;

                if (txtTag != null && !String.IsNullOrEmpty(txtTag.Text.Trim()))
                {
                    Tag newTag = new Tag { TagValue = txtTag.Text.Trim().ToLower() };

                    bool containsTag = false;

                    foreach (Tag t in NewsItem.Tags)
                    {
                        if (t.TagValue == newTag.TagValue)
                        {
                            containsTag = true;
                            break;
                        }
                    }

                    if (!containsTag)
                    {
                        NewsItem.Tags.Add(newTag);
                    }
                }
            }

            //raise the event so the client code can save to the DB
            if (Save != null)
            {
                Save(this, EventArgs.Empty);
            }
        }

        #endregion

        #region Methods

        protected void FullTextCheckedChanged()
        {
            if (rbFullText.Checked)
            {
                pnlFullText.Visible = true;
                if (IsEditMode)
                {
                    txtFullText.Text = (NewsItem.Text ?? "").Replace("<br />", Environment.NewLine).Replace(" &nbsp;", "  ").RemoveHtmlTags().HtmlDecode();
                    edFullText.Content = txtFullText.Text;
                    ToggleFullText(NewsItem.IsTextHtml);
                }
            }
            else
            {
                pnlFullText.Visible = false;
            }
        }


        private void ToggleFullText(bool isHtml)
        {
            if (isHtml)
            {
                ddlIsFullTextHtml.SelectedValue = "html";
                mvFullTextEditorType.ActiveViewIndex = 1; //index of the HTML View
                rfvFullText.ControlToValidate = edFullText.ID;
                edFullText.Content = txtFullText.Text;
            }
            else
            {
                ddlIsFullTextHtml.SelectedValue = "pt";
                mvFullTextEditorType.ActiveViewIndex = 0; //index of the Text View
                rfvFullText.ControlToValidate = txtFullText.ID;
                txtFullText.Text = edFullText.Content;
            }
        }

        private void ToggleShortText(bool isHtml)
        {
            if (isHtml)
            {
                ddlIsShortTextHtml.SelectedValue = "html";
                mvShortTextEditorType.ActiveViewIndex = 1; //index of the HTML View
                rfvShortText.ControlToValidate = edShortText.ID;
                edShortText.Content = txtShortText.Text;
            }
            else
            {
                ddlIsShortTextHtml.SelectedValue = "pt";
                mvShortTextEditorType.ActiveViewIndex = 0; //index of the Text View
                rfvShortText.ControlToValidate = txtShortText.ID;
                txtShortText.Text = edShortText.Content;
            }
        }

        #endregion

    }
}
